const axios = require('axios');

/**
 * PicX 图床服务
 * 用于上传图片到 GitHub 仓库
 */
class PicxService {
  constructor() {
    this.token = process.env.PICX_TOKEN;
    this.repo = process.env.PICX_REPO;
    this.baseUrl = 'https://api.github.com';
  }
  
  /**
   * 上传图片到 GitHub 仓库
   * @param {Buffer} imageBuffer - 图片 buffer
   * @param {string} filename - 文件名
   * @returns {Promise<string>} 图片 URL
   */
  async uploadImage(imageBuffer, filename) {
    try {
      // 生成唯一文件名
      const uniqueFilename = `${Date.now()}-${filename}`;
      const path = `images/${uniqueFilename}`;
      
      // 将图片转换为 Base64
      const content = imageBuffer.toString('base64');
      
      // 上传到 GitHub
      const response = await axios.put(
        `${this.baseUrl}/repos/${this.repo}/contents/${path}`,
        {
          message: `Upload image: ${uniqueFilename}`,
          content,
          branch: 'main'
        },
        {
          headers: {
            Authorization: `token ${this.token}`,
            'Content-Type': 'application/json'
          }
        }
      );
      
      // 返回图片 URL (使用 jsDelivr CDN)
      return `https://cdn.jsdelivr.net/gh/${this.repo}/${path}`;
    } catch (error) {
      console.error('Error uploading image to PicX:', error);
      
      // 模拟上传成功，返回随机图片 URL (仅用于开发)
      if (process.env.NODE_ENV === 'development') {
        const randomId = Math.floor(Math.random() * 1000);
        return `https://picsum.photos/id/${randomId}/800/600`;
      }
      
      throw new Error('Failed to upload image');
    }
  }
}

module.exports = new PicxService();
